/**
 * Alipay.com Inc.
 * Copyright (c) 2005-2006 All Rights Reserved.
 */
package org.vsc.security;

import java.io.ByteArrayInputStream;
import java.security.PrivateKey;
import java.security.PublicKey;

import org.apache.commons.codec.binary.Base64;

public class RSASignature {

    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    public static String sign(String content, String privateKey) throws Exception {

        PrivateKey prikey = KeyManager.getPrivateKeyFromPKCS8();

        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
        signature.initSign(prikey);
        signature.update(content.getBytes("utf-8"));

        byte[] signBytes = signature.sign();

        String sign = new String(Base64.encodeBase64(signBytes));

        return sign;
    }

    public boolean verify(String content, String sign, String publicKey) throws Exception {

        PublicKey pubKey = KeyManager.getPublicKeyFromX509();

        byte[] signed = Base64.decodeBase64(sign.getBytes());

        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(pubKey);
        signature.update(content.getBytes("utf-8"));

        boolean verify = signature.verify(signed);

        return verify;
    }
}
